<template>
  <div class="context-menu-target" ref="target">
    <slot></slot>
  </div>
</template>
<script setup>
import { inject, ref, onMounted, onUnmounted } from "vue";
const showMenu = inject("showMenu");
const hideMenu = inject("hideMenu");
const emit = defineEmits(["select"]);
const target = ref();

// 初始化事件监听
onMounted(() => {
  if (!target.value) {
    return;
  }

  // 为目标元素添加右键事件
  target.value.addEventListener("contextmenu", (e) => {
    showMenu(e, (menu) => {
      emit("select", menu);
    });
  });

  // 点击其他区域关闭菜单
  document.addEventListener("click", hideMenu);

  // 窗口大小改变时关闭菜单
  window.addEventListener("resize", hideMenu);
});

// 清理事件监听
onUnmounted(() => {
  if (target.value) {
    target.value.removeEventListener("contextmenu", showMenu);
  }
  document.removeEventListener("click", hideMenu);
  window.removeEventListener("resize", hideMenu);
});
</script>
